<?php
namespace App\Services\Wechat\sdk\components\messageCrypt;

/**
 * PKCS7Encoder class
 *
 * 提供基于PKCS7算法的加解密接口.
 */
class Pkcs7Encoder
{
	public static $block_size = 32;
	public $_key = '';

	/**
	 * 对需要加密的明文进行填充补位
	 * @param $text 需要进行填充补位操作的明文
	 * @return 补齐明文字符串
	 */
	function encode($text)
	{
		$block_size = Pkcs7Encoder::$block_size;
		$text_length = strlen($text);
		//计算需要填充的位数
		$amount_to_pad = Pkcs7Encoder::$block_size - ($text_length % Pkcs7Encoder::$block_size);
		if ($amount_to_pad == 0) {
			$amount_to_pad = Pkcs7Encoder::$block_size;
		}
		//获得补位所用的字符
		$pad_chr = chr($amount_to_pad);
		$tmp = "";
		for ($index = 0; $index < $amount_to_pad; $index++) {
			$tmp .= $pad_chr;
		}
		return $text . $tmp;
	}

	/**
	 * 对解密后的明文进行补位删除
	 * @param decrypted 解密后的明文
	 * @return 删除填充补位后的明文
	 */
	function decode($text)
	{

		$pad = ord(substr($text, -1));
		if ($pad < 1 || $pad > 32) {
			$pad = 0;
		}
		return substr($text, 0, (strlen($text) - $pad));
	}

	/**
     * 对密文进行解密
     *
     * @param string $encrypted 需要解密的密文
     * @return string 解密得到的明文
     */
    public function decrypt($encrypted) {
        $iv = substr($this->_key, 0, 16);
        $decrypted = openssl_decrypt($encrypted, 'AES-256-CBC', $this->_key, OPENSSL_ZERO_PADDING, $iv);
        //去除补位字符
        $result = $this->decode($decrypted);
        //去除16位随机字符串 加密时添加16为随机字符串
        if (strlen($result) < 16) {
            return "";
        }
        $content = substr($result, 16, strlen($result));
        $lenList = unpack("N", substr($content, 0, 4));
        $contentLen = $lenList[1];

        return substr($content, 4, $contentLen);
    }
}

?>